<template>
    <div class="app-container">
        <el-form class="lookForm" :model="queryParams" ref="queryForm" size="mini" :inline="true" label-width="140px">
            <el-form-item label="岗位名称" prop="postName">
                <el-input v-model="queryParams.postName" placeholder="请输入岗位名称" clearable
                    @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="设岗部门" prop="deptName">
                <el-input v-model="queryParams.deptName" placeholder="请输入设岗部门" clearable
                    @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="审核状态" prop="applyStatus">
                <el-select v-model="queryParams.applyStatus" placeholder="请选择审核状态" clearable>
                    <el-option v-for="dict in dict.type.qgzx_apply_status" :key="dict.value" :label="dict.label"
                        :value="dict.value" />
                </el-select>
            </el-form-item>
            <el-form-item label="结算月份" prop="applyTime">
                <el-date-picker clearable v-model="queryParams.applyTime" type="month" value-format="yyyy-MM-dd"
                    placeholder="请选择结算月份">
                </el-date-picker>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="success" plain icon="el-icon-finished" size="mini"
                    @click="manyAudit('6')">批量同意</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="danger" plain icon="el-icon-close" size="mini"
                    @click="manyAudit('10')">批量拒绝</el-button>
            </el-col>

            <el-col :span="1.5">
                <el-button type="success" plain icon="el-icon-s-claim" size="mini" @click="deptVClick">按部门审核</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="success" plain icon="el-icon-position" size="mini"
                    @click="oneClickAudit">一键通过所有资助办审核通过</el-button>
            </el-col>
        </el-row>

        <el-table v-loading="loading" :data="tableData" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />

            <el-table-column label="#" align="center" prop="id" />
            <el-table-column label="学号" align="center" prop="stuNo" />

            <el-table-column label="姓名" align="center" prop="stuName" />
            <el-table-column label="学院" align="center" prop="stuDept" />

            <el-table-column label="岗位名称" align="center" prop="postName" />
            <el-table-column label="设岗部门" align="center" prop="deptName" />
            <el-table-column label="岗位类型" align="center" prop="postType" />
            <el-table-column label="工作时长" align="center">
                <template v-slot="{ row }">
                    {{ row.postType == "固定岗位A" ? row.totalTime + "天" : row.totalTime + "小时" }}
                </template>
            </el-table-column>
            <el-table-column label="结算月份" align="center">
                <template v-slot="{ row }">
                    {{ formatDate(row.applyTime) }}
                </template>
            </el-table-column>
            <!-- <el-table-column label="薪资" align="center" prop="applyStatus">
                <template slot-scope="scope">
                    {{ scope.row.totalTime * 15 }}
                </template>
            </el-table-column> -->

            <el-table-column label="审核状态" align="center" prop="applyStatus">
                <template slot-scope="scope">
                    <dict-tag :options="dict.type.qgzx_apply_status" :value="scope.row.applyStatus" />
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button size="mini" type="text" icon="el-icon-edit" @click="lookVClick(scope.row)">审核</el-button>
                </template>
            </el-table-column>
        </el-table>



        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize" @pagination="getList" />


        <el-dialog title="查看" :visible.sync="lookV">
            <el-steps :active="getStep(lookForm)">
                <el-step title="指导老师填报薪资" description=""></el-step>

                <el-step title="部门领导审批" :status="isEmpty(lookForm.deptCmt) ? 'wait' : getStepStatus(lookForm.deptCmt)"
                    :description="isEmpty(lookForm.deptCmt) ? '' : lookForm.deptCmt"></el-step>

                <el-step title="资助办审批" :status="isEmpty(lookForm.highCmt) ? 'wait' : getStepStatus(lookForm.highCmt)"
                    :description="isEmpty(lookForm.highCmt) ? '' : lookForm.highCmt"></el-step>

                <el-step title="学工领导审批" :status="isEmpty(lookForm.finalCmt) ? 'wait' : getStepStatus(lookForm.finalCmt)"
                    :description="isEmpty(lookForm.finalCmt) ? '' : lookForm.finalCmt"></el-step>
            </el-steps>
            <hr />
            <el-form class="lookForm" size="mini" label-width="148px">
                <el-form-item label="学工处意见">
                    <el-radio-group v-model="auditForm.finalCmt">
                        <el-radio :label="'同意'">同意</el-radio>
                        <el-radio :label="'拒绝'">拒绝</el-radio>
                        <el-radio :label="'驳回'">驳回</el-radio>
                    </el-radio-group>
                </el-form-item>

                <el-form-item label="学工处意见">
                    <el-upload :limit="1" class="avatar-uploader" :file-list="upload.fileList" :action="upload.url"
                        :headers="upload.headers" :show-file-list="false" :on-success="handleAvatarSuccess">
                        <img v-if="auditForm.finalSign" :src="baseurl + auditForm.finalSign" width="200px" height="50px"
                            class="avatar">
                        <span v-else> 点击上传</span>
                    </el-upload>
                </el-form-item>
                <el-form-item label="">
                    <el-button @click="doAudit">审核</el-button>
                </el-form-item>

            </el-form>
            <hr />
            <el-form class="lookForm" size="mini" label-width="148px">
                <el-form-item label="学生">
                    <el-input v-model="lookForm.stuName" readonly />
                </el-form-item>
                <el-form-item label="岗位">
                    <el-input v-model="lookForm.postName" readonly />
                </el-form-item>
                <el-form-item label="总工作时长">
                    <el-input v-model="lookForm.totalTime" readonly />
                </el-form-item>
                <el-form-item label="指导老师签章">
                    <img v-if="lookForm.applySign" :src="baseurl + lookForm.applySign" width="200px" height="50px"
                        class="avatar">
                </el-form-item>
                <el-form-item label="部门意见" v-if="!isEmpty(lookForm.deptCmt)">
                    <el-input v-model="lookForm.deptCmt" />
                </el-form-item>
                <el-form-item label="部门签章" v-if="!isEmpty(lookForm.deptSign)">
                    <img v-if="lookForm.deptSign" :src="baseurl + lookForm.deptSign" width="200px" height="50px"
                        class="avatar">
                </el-form-item>
                <el-form-item label="资助办意见" v-if="!isEmpty(lookForm.highCmt)">
                    <el-input v-model="lookForm.highCmt" />
                </el-form-item>
                <el-form-item label="资助办签章" v-if="!isEmpty(lookForm.highSign)">
                    <img v-if="lookForm.highSign" :src="baseurl + lookForm.highSign" width="200px" height="50px"
                        class="avatar">
                </el-form-item>
            </el-form>
        </el-dialog>


        <el-dialog title="按部门审核" :visible.sync="deptV" append-to-body :close-on-click-modal="false">
            <el-row :gutter="10" class="mb8">
                <el-col :span="1.5">
                    <el-button type="success" plain icon="el-icon-finished" size="mini"
                        @click="deptAudit('6')">一键通过</el-button>
                </el-col>
                <el-col :span="1.5">
                    <el-button type="danger" plain icon="el-icon-close" size="mini"
                        @click="deptAudit('10')">批量拒绝</el-button>
                </el-col>
            </el-row>
            <el-empty v-if="isEmpty(audit_dept_list)" description="暂无待审批记录"></el-empty>

            <el-row>
                <el-col v-for="(item, index) in audit_dept_list" :key="index" :span="8">
                    <el-card style="cursor: pointer;margin-top: 10px;" class="box-card" shadow="never"
                        :class="{ 'active': isSelected(item.deptCode) }" @click.native="selectCollege(item.deptCode)">
                        <div class="text item">
                            {{ '部门名称：' + item.deptName }}
                        </div>
                        <div class="text item">
                            {{ '部门代码：' + item.deptCode }}
                        </div>
                        <div class="text item">
                            {{ '待审核数量：' + item.number }}
                        </div>
                    </el-card>
                </el-col>
            </el-row>

        </el-dialog>

    </div>
</template>
<script>

import { CheckImgExists, fullLoading, isEmpty } from "@/api/helpFunc";
import TeacherOwnStuPostSelect from "@/views/workstudy/components/TeacherOwnStuPostSelect";

import { getOwnSign } from "@/api/workstudy/post";
import { getToken } from "@/utils/auth";


import { oneClickAudit, doAudit, finalDeptAuditPass, finalDeptAuditUnPass, listFinal as getList, listFinalAuditByDept, manyAudit } from "@/api/workstudy/money";


export default {
    name: "Money",
    dicts: ['qgzx_apply_status'],
    components: { TeacherOwnStuPostSelect },
    data() {
        return {
            editV: false,
            applyForm: {
                stuPostId: null
            },
            upload: {
                headers: { Authorization: "Bearer " + getToken() },
                // 上传的地址
                url: process.env.VUE_APP_BASE_API + "/common/upload",
                fileList: []
            },
            baseurl: process.env.VUE_APP_BASE_API + "/",
            isEmpty,
            loading: false,

            tableData: [],
            total: 0,
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                postName: null
            },
            lookForm: {},

            lookV: false,

            auditForm: {
                id: null,
                deptCmt: null
            },

            selectedId: [],

            deptV: false,
            audit_dept_list: [],

            selectDeptCode: []
        }
    },
    created() {
        this.getList();
    },
    methods: {
        oneClickAudit() {
            this.$confirm('您确定要一键通过么', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                let loading = fullLoading(this);
                let res = await oneClickAudit();
                loading.close();
                if (res.code == 200) {
                    this.$message.success(res.msg);
                    this.getList();
                }
            })
        },
        formatDate(dateStr) {
            const date = new Date(dateStr);
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份是从0开始的，所以需要+1
            return `${year}年${month}月`;
        },
        //此方法用于判断步骤条当前步骤的状态
        getStepStatus(data) {
            if (data == "同意") {
                return 'success';
            } else {
                return 'error';
            }
        },

        //此方法用于判断步骤条到哪个步骤了
        getStep(data) {
            if (!isEmpty(data.deptCmt)) { //判断部门领导有没有审批
                return 2;
            } else if (!isEmpty(data.highCmt)) { //判断资助办有没有审批
                return 3;
            } else if (!isEmpty(data.finalCmt)) { //判断学工处有没有审批
                return 4;
            } else {
                return 1;
            }
        },
        deptVClick() {
            this.listFinalAuditByDept();
            this.deptV = true;
        },
        deptAudit(val) {
            let msg = val == "6" ? "同意" : "拒绝";

            let sdata = [...this.selectDeptCode];
            if (isEmpty(sdata)) {
                this.$message.info("请选择需要一键审批的部门");
                return;
            }
            this.$confirm('您确定要一键' + msg + "吗", '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                if (val == "6") {
                    let loading = fullLoading(this);
                    let res = await finalDeptAuditPass(sdata);
                    loading.close();
                    if (res.code == 200) {
                        this.$message.success(res.msg);
                    }
                } else {
                    let loading = fullLoading(this);
                    let res = await finalDeptAuditUnPass(sdata);
                    loading.close();
                    if (res.code == 200) {
                        this.$message.success(res.msg);
                    }
                }

                this.getList();
                this.listFinalAuditByDept();
            }).catch(() => {

            });
        },
        selectCollege(code) {
            if (!this.selectDeptCode.includes(code)) return this.selectDeptCode.push(code)
            this.selectDeptCode = this.selectDeptCode.filter(i => i !== code)
        },
        isSelected(code) {
            return this.selectDeptCode.includes(code)
        },
        async listFinalAuditByDept() {
            let loading = fullLoading(this);
            let res = await listFinalAuditByDept();
            loading.close();
            if (res.code == 200) {
                this.audit_dept_list = [...res.data];
                console.log(this.audit_dept_list);
            }
        },

        handleSelectionChange(val) {
            this.selectedId = val.map(x => x.id);
        },
        async manyAudit(val) {
            if (isEmpty(this.selectedId)) {
                this.$message.info("请勾选记录");
                return;
            }

            let loading = fullLoading(this);
            let res1 = await getOwnSign();
            loading.close();
            if (res1.code == 200) {
                let data = { ...res1.data };
                if (isEmpty(data.signature)) {
                    this.$confirm('您的签名尚未上传', '提示', {
                        confirmButtonText: '点我前往',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        this.$router.push("/user/profile")
                    }).catch(() => {

                    });
                } else {
                    let msg = "";
                    if (val == '6') {
                        msg = "同意";
                    } else {
                        msg = "拒绝";
                    }
                    let sign = data.signature;

                    this.$confirm('您确定要批量' + msg + '吗?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(async () => {
                        let sdata = [];
                        this.selectedId.map(x => {
                            let temp = {
                                id: x,
                                applyStatus: val,
                                finalCmt: msg,
                                finalSign: sign
                            }
                            sdata.push(temp);
                        });

                        let loading = fullLoading(this);
                        let res = await manyAudit(sdata);
                        loading.close();
                        if (res.code == 200) {
                            this.$message.success(res.msg);
                            this.getList();
                        }
                    }).catch(() => {

                    });
                }
            }
        },

        async lookVClick(row) {
            this.lookForm = {};
            this.auditForm = {};
            let loading = fullLoading(this);
            let res = await getOwnSign();
            loading.close();
            if (res.code == 200) {
                let data = { ...res.data };
                if (isEmpty(data.signature)) {
                    this.$confirm('您的签名尚未上传', '提示', {
                        confirmButtonText: '点我前往',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        this.$router.push("/user/profile")
                    }).catch(() => {

                    });
                } else {
                    this.auditForm.finalSign = data.signature;
                    this.auditForm.id = row.id;
                    this.lookForm = { ...row };
                    this.lookV = true;
                }
            }

        },

        async getList() {
            this.loading = true;
            let res = await getList(this.queryParams);
            this.loading = false;
            if (res.code == 200) {
                this.tableData = [...res.rows];
                this.total = res.total;
            }
        },
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },

        handleAvatarSuccess(response, file, fileList) {
            this.auditForm.finalSign = response.fileName;
            this.upload.fileList = [];
            this.$forceUpdate();
        },
        async doAudit() {
            let sdata = { ...this.auditForm };
            if (isEmpty(sdata.finalCmt)) {
                this.$message.info("请选择意见");
                return;
            }
            if (isEmpty(sdata.finalSign)) {
                this.$message.info("请上传签章");
                return;
            }

            if (!CheckImgExists(this.baseurl + sdata.finalSign)) {
                this.$message.info("签名失效，请重新上传");
                return;
            }

            if (sdata.finalCmt == '同意') {
                sdata.applyStatus = '6';
            } else {
                sdata.applyStatus = "10";
            }

            if (sdata.finalCmt == '驳回') {
                sdata.applyStatus = "11"; //驳回
                this.$prompt('请输入驳回原因', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    inputPattern: /\S/,
                    inputErrorMessage: '请填写'
                }).then(async ({ value }) => {
                    sdata.auditRemark = value;

                    let loading = fullLoading(this);
                    let res = await doAudit(sdata);
                    loading.close();
                    if (res.code == 200) {
                        this.getList();
                        this.$message.success(res.msg);
                        this.lookV = false;
                    }

                }).catch(() => {

                });
            } else {

                let loading = fullLoading(this);
                let res = await doAudit(sdata);
                loading.close();
                if (res.code == 200) {
                    this.getList();
                    this.$message.success(res.msg);
                    this.lookV = false;
                }
            }
        }
    }
}


</script>

<style scoped lang="scss">
.lookForm {
    .el-form-item {
        margin-bottom: 5px;
    }
}

.active {
    box-shadow: 0px 0px 8px 2px rgba(0, 120, 255, 0.5);
}

.text {
    font-size: 14px;
}

.item {
    margin-bottom: 18px;
}
</style>